package com.cn.wanxi.servlet.news;

import com.cn.wanxi.model.NewsModel;
import com.cn.wanxi.model.PlateModel;
import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.service.INewsPlateService;
import com.cn.wanxi.service.INewsService;
import com.cn.wanxi.service.impl.NewsPlateServiceImpl;
import com.cn.wanxi.service.impl.NewsServiceImpl;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/newsAdd")
public class NewsAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        1.拿到页面传递过来的值
        String status = req.getParameter("status");
        String title = req.getParameter("title");
        String plateId = req.getParameter("plateId");
        String author = req.getParameter("author");
        String content = req.getParameter("content");
        String isTop = req.getParameter("isTop");

//        2.封装model
        NewsModel newsModel = new NewsModel();
        newsModel.setTitle(title);

        newsModel.setStatus("1".equals(status) ? 1 : 0);
        newsModel.setAuthor(author);
        newsModel.setContent(content);
        newsModel.setIsTop("1".equals(isTop) ? 1 : 0);
        newsModel.setPlateId(plateId == null ? 0 : Integer.parseInt(plateId));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss sss");
        newsModel.setCreateTime(simpleDateFormat.format(new Date()));
//        3.调用服务逻辑层
        INewsService iNewsService = new NewsServiceImpl();
        ResultModel resultModel = iNewsService.add(newsModel);
//        4.返回数据
        JSONArray jsonArray = JSONArray.fromObject(resultModel);
        resp.getWriter().println(jsonArray);
    }
}
